<?php
namespace WXAPI\Controller;
require_once './ThinkPHP/Library/Vendor/qiniuyun/autoload.php';
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Think\Controller;
use Think\Log;

ini_set('max_execution_time', '0');
ini_set('memory_limit', '888M');
class ErpController extends BaseController{
    /**
     * 析构流函数
     */
    public function  __construct() {
        parent::__construct();
        if(CONTROLLER_NAME == 'Erp'){
             $whiteList=array('8.134.24.132');
             $visitorIp=$_SERVER['REMOTE_ADDR'];
             if (in_array($visitorIp,$whiteList)) {

             } else {
                 //echo '禁止访问';exit;
             }
        }
    }

    public function index(){
        echo I('callback')."(".json_encode([
                'code'=>'200',
                'infos'=>'连接成功！'
            ]).")";
    }
    public function erp_api(){
        echo 'SELECT top 100 * FROM ptype';
    }
    public function yongyou(){
        echo '用友数据';
    }

    public function guanjia(){
        $fullpath = 'images/202304/source_img/0_G_1682712789588.jpg';
        $filePath = './'.$fullpath;
        $accessKeyId = "LTAI5tH4TjV55x3KhizCjvHg";
        $accessKeySecret = "LUC1BQgAxam3ihfi2JRo8zohOVDAN2";
        $endpoint = "https://haoshuangkuaistatic.huamanhn.com/";
        $bucket= "haoshuangkuai-bucket";

        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, true);
        $ossClient->uploadFile($bucket, $fullpath, $filePath);


    }

    /**
     * 查询产品
     */
    public function getGoodsData()
    {
        $cPage = I('p',0);
        $userName = I('username');
        $passWord = I('password');
        $cPage = $cPage * 10;
        $seller = M('seller')->where(array('seller_name'=>$userName))->find();
        $store_id = $seller['store_id']; //获取店铺id
        $goods = M('goods')->where(['is_on_sale'=>1,'store_id'=>$store_id])->limit($cPage, 10)->select(); //获取店铺产品
        foreach ($goods as $key=>$good){
            $goods[$key]['images'] = M('goods_images')->field('image_url,sort_id')->where(['goods_id'=>$good['goods_id']])->select();
            $goods[$key]['goodstype_name'] = M('store_goods_class')->where(['cat_id'=>$good['store_cat_id1']])->getField('cat_name');
            $spec = M('spec_item a')->field('a.*,b.name as spec_name,b.order,c.name as type_name,d.src')
                ->join('ty_spec b on a.spec_id = b.id','LEFT')
                ->join('ty_goods_type c on b.goods_type_id = c.id','LEFT')
                ->join('ty_spec_image d on a.id = d.spec_image_id','LEFT')
                ->where(['a.goods_id'=>$good['goods_id'],'a.store_id'=>$store_id])->select();
            $goods[$key]['spec'] = $spec;

            $specPrice = M('spec_goods_price')->where(['goods_id'=>$good['goods_id']])->select();
            $goods[$key]['spec_price'] = $specPrice;
        }

        $json_str = json_encode(['status'=>1,'data'=>$goods,'msg'=>'获取成功'],true);
        exit($json_str);
    }

    /**
     * 获取商品的sku
     */
    public function getGoodsSku(){
        $userName = I('username');
        $seller = M('seller')->where(array('seller_name'=>$userName))->find();
        $store_id = $seller['store_id']; //获取店铺id
        $spec_goods_price = M('spec_goods_price')->where(['store_id'=>$store_id])->select(); //获取店铺产品

        $json_str = json_encode(['status'=>1,'data'=>$spec_goods_price,'msg'=>'获取成功'],true);
        exit($json_str);
    }

    /**
     * 查询订单
     */
    public function getOrderData()
    {
        $userName = I('username');
        $passWord = I('password');
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('~', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        $seller = M('seller')->where(array('seller_name'=>$userName))->find();
        $store_id = $seller['store_id']; //获取店铺id

        $map = " 1 ";
        $map .= " and a.store_id = {$store_id} ";
        $map .= " and a.order_status = 0 and a.dayin_store = 0";
        if($timegap){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        $order_list =  M('order as a')
            ->field('a.*,b.mobile,b.company,b.biaoshi')
            ->join('ty_users b on a.user_id=b.user_id','LEFT')
            ->group('a.order_id')
            ->where($map)->where($condition)->order("a.order_id desc")->select();

        if($order_list){
            //获取订单商品
            foreach($order_list as $k=>$v){
                $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
                //订单总额
                $sql = "SELECT og.*,g.original_img FROM __PREFIX__order_goods og LEFT JOIN __PREFIX__goods g ON g.goods_id = og.goods_id WHERE order_id = ".$v['order_id'];
                $data = M()->query($sql);

                foreach ($data as $key => $value)
                {
                    $data[$key]['image'] = C('MYOSS')['url'].$value['original_img'];
                }
                $order_list[$k]['goods_list'] = $data;
            }
        }

        $json_str = json_encode(['status'=>1,'data'=>$order_list,'msg'=>'获取成功'],true);
        exit($json_str);
    }
    /**
     * 修改订单
     */
    public function getSaveOrder()
    {
        $field = I('field');
        $value = I('value');
        $order_sn = I('order_sn');


        M('order')->where(['order_sn'=>$order_sn])->save([$field=>$value]);
        $json_str = json_encode(['status'=>1,'data'=>[],'msg'=>'修改成功'],true);
        exit($json_str);
    }


    /**
     * 保存订单件数
     */
    public function getSaveJian()
    {
        $order_id = I('order_id'); //原始订单号
        $value = I('count');//数量
        M('order_jian')->where('order_id='.$order_id)->delete();//删除出入库重写写入记录
        for($i=1;$i<=(int)$value;$i++){
            M('order_jian')->add([
                "order_id"=>$order_id,
                "ruku_num"=>$i,
                "chuku_num"=>$i
            ]);
        }

        $json_str = json_encode(['status'=>1,'data'=>[],'msg'=>'修改成功'],true);
        exit($json_str);
    }


  /**
     * 删除店铺
     * @return void
     */
    public function deleteStore()
    {
        $userName = I('username');
        $seller = M('seller')->where(array('seller_name'=>$userName))->find();
        $store_id = $seller['store_id']; //获取店铺id
        if($store_id){

            $goods = M('goods')->where('store_id='.$store_id)->select();

            $accessKey ="TwLrl3V9LTBaO8sFt1gi-8A9UtVZRmy3xRi8yCOs";
            $secretKey = "P3sjrkVGEH8TBO2BbmnqJNe31iWDHwqJDAuy-kXg";
            $bucket = "tlcsc";
            $auth = new Auth($accessKey, $secretKey);
            $config = new Config();
            $bucketManager = new BucketManager($auth,$config);


            foreach ($goods as $good){
                $goodimgs = M('goods_images')->where('goods_id='.$good['goods_id'])->select();
                foreach ($goodimgs as $goodimg){
                    M('goods_images')->where(['img_id'=>$goodimg['img_id']])->delete();
                    $object1 = str_replace('/Public/', 'Public/', $goodimg['image_url']);
                    $file = '.'.$goodimg['image_url'];
                    unlink($file);
                    $err = $bucketManager->delete($bucket, $object1);
                }
                $file = '.'.$good['original_img'];
                unlink($file);
                $object2 = str_replace('/Public/', 'Public/', $good['original_img']);
                $err = $bucketManager->delete($bucket, $object2);
            
            }


            M('goods_type')->where('store_id='.$store_id)->delete();
            M('goods')->where('store_id='.$store_id)->delete();
            M('spec_image')->where('store_id='.$store_id)->delete();
            M('spec_goods_price')->where('store_id='.$store_id)->delete();
            M('spec')->where('store_id='.$store_id)->delete();
            M('spec_item')->where('store_id='.$store_id)->delete();

            M('order')->where('store_id='.$store_id)->delete();
            M('store_goods_class')->where('store_id='.$store_id)->delete();
            M('order_goods')->where('store_id='.$store_id)->delete();
            M('prom_goods')->where('store_id='.$store_id)->delete();

            $json_str = json_encode(['status'=>1,'data'=>[],'msg'=>'删除成功'],true);
            exit($json_str);
        }else{
            $json_str = json_encode(['status'=>0,'data'=>[],'msg'=>'找不到店铺'],true);
            exit($json_str);
        }

    }


    /**
     * store_name  店铺账号
     * from_plat  来源平台
     * goods_data  产品数据
     * 保存商品
     */
    public function saveGoods()
    {
        $userName = $_POST['store_name'];
        $fromPlatUrl = $_POST['from_plat'];
        $seller = M('seller')->where(array('seller_name'=>$userName))->find();
        if(!$seller){
            $json_str = json_encode(['status'=>0,'data'=>[],'msg'=>'找不到目标店铺'],true);
            exit($json_str);
        }

        $store_id = $seller['store_id']; //获取店铺id
        $args = json_decode($_POST['goods_data'],true);
       Log::record($_POST['goods_data'],'debug');
       Log::record($args,'debug');
        if($args){
            if(isset($args['images'])){
                $data['images'] = $args['images'];
            }else{
                $data['images'] = [];
            }
            $data['spec'] = $args && $args['spec'] ? $args['spec'] : [];
            $data['spec_price'] = $args && $args['spec_price'] ? $args['spec_price'] : [];
            unset($args['images']);unset($args['spec']);unset($args['spec_price']);
            unset($args['goods_id']);unset($args['store_cat_id1']);unset($args['store_cat_id2']);unset($args['store_cat_id3']);
            unset($args['prom_id']);unset($args['goods_sn']);
            $args['on_time'] = time();
            $data['goods'] = $args;
            $goods_name = $data['goods']['goods_name'];

            //处理店铺分类
            if(isset($data['goods']['goodstype_name'])){
                $goodstype_name = $data['goods']['goodstype_name']; //店铺分类
                $store_class_id = M('store_goods_class')->where(['store_id'=>$store_id,'cat_name'=>$goodstype_name])->getField('cat_id');
                if(!$store_class_id){
                    $store_class_id = M('store_goods_class')->add(['store_id'=>$store_id,'cat_name'=>$goodstype_name,'is_show'=>1]);
                }

                $data['goods']['store_cat_id1'] = $store_class_id;
            }


            $data['goods']['store_id'] = $store_id;
            $goods = M('goods')->where(['goods_name'=>$goods_name,'store_id'=>$store_id])->find();
            if($goods){
                $json_str = json_encode(['status'=>0,'data'=>['goods_name'=>$goods_name],'msg'=>$goods_name.'已经存在'],true);
                exit($json_str);
            }

            function downloadImage($url,$fromPlatUrl)
            {
                $url = $fromPlatUrl.$url;
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
                $file = curl_exec($ch);
                curl_close($ch);
                saveAsImage($url, $file);
            }

            function saveAsImage($url, $file)
            {

                $accessKey ="TwLrl3V9LTBaO8sFt1gi-8A9UtVZRmy3xRi8yCOs";
                $secretKey = "P3sjrkVGEH8TBO2BbmnqJNe31iWDHwqJDAuy-kXg";
                $bucket = "tlcsc";

                $filename = pathinfo($url, PATHINFO_BASENAME);
                $dirname = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_DIRNAME);
                $path =   substr($dirname,1);
                $fullpath =  $path . '/' . $filename;
                Log::record($fullpath,'DEBUG');

                // 如果目录不存在，则创建
                if(!is_dir($path)) {
                    mkdir($path, 0777, true);
                }
                if(file_exists($fullpath)) {
   
                    //sofwu code qiniu oss
                    // 构建鉴权对象
                   $auth = new Auth($accessKey, $secretKey);
                    $object = str_replace('/Public/', 'Public/', $fullpath);
                    $filePath = './'.$fullpath;
                    // 生成上传 Token
                    $token = $auth->uploadToken($bucket,$object);
                    $uploadMgr = new UploadManager();
                    $uploadMgr->putFile($token, $object, $filePath, null, 'application/octet-stream', true, null, 'v2');
                    //$this->output->writeln("【已存在】输出路径" . $fullpath);
    
                } else {
                    $resource = fopen($fullpath, 'a');
                    fwrite($resource, $file);

                    //sofwu code qiniu oss
                    // 构建鉴权对象
                    $auth = new Auth($accessKey, $secretKey);
                    // 生成上传 Token
                    $token = $auth->uploadToken($bucket);
                    $object = str_replace('/Public/', 'Public/', $fullpath);
                    $filePath = './'.$fullpath;
                    $uploadMgr = new UploadManager();
                    $uploadMgr->putFile($token, $object, $filePath, null, 'application/octet-stream', true, null, 'v2');
                    fclose($resource);
                    //$this->output->writeln("【已保存】输出路径" . $fullpath);
                }
            }

            downloadImage($data['goods']['original_img'],$fromPlatUrl); //下载大图

            $goodsId = M('goods')->add($data['goods']); //同步产品

            //同步图册
            if(isset($data['images'])){
                foreach ($data['images'] as $image){
                    downloadImage($image['image_url'],$fromPlatUrl);
                    $image['goods_id'] = $goodsId;
                    M('goods_images')->add($image);
                }
            }

            //同步规格
            if(isset($data['spec'])){
                foreach ($data['spec'] as $datum){
                    $datum['store_id'] = $store_id;
                    unset($datum['id']);unset($datum['spec_id']);
                    $goodsType = M('goods_type')->where(['name'=>$datum['type_name'],'store_id'=>$store_id])->find();
                    $goodsTypeId = $goodsType['id'];
                    $goodsSpec = M('spec')->where(['name'=>$datum['spec_name'],'store_id'=>$store_id,'goods_type_id'=>$goodsTypeId])->find();
                    $goodsSpecId = $goodsSpec['id'];
                    if(!$goodsType){
                        $goodsTypeId = M('goods_type')->add(['name'=>$datum['type_name'],'store_id'=>$store_id]);
                    }

                    //保存产品对应的规格
                    M('goods')->where(['goods_id'=>$goodsId])->save(['goods_type'=>$goodsTypeId]);

                    if(!$goodsSpec){
                        $goodsSpecId = M('spec')->add(['name'=>$datum['spec_name'],'order'=>$datum['order'],'store_id'=>$store_id,'goods_type_id'=>$goodsTypeId]);
                    }

                    $specItemId = M('spec_item')->add(['spec_id'=>$goodsSpecId,'item'=>$datum['item'],'store_id'=>$store_id,'goods_id'=>$goodsId,'sort'=>$datum['sort']]);

                    if(isset($datum['src'])){
                        //处理图片
                        downloadImage($datum['src'],$fromPlatUrl);
                    }else{
                        $datum['src']="";
                    }
                    $datum['src'] = str_replace('','https://haoshuangkuaistatic.huamanhn.com/',$datum['src']);
                    M('spec_image')->add(['spec_image_id'=>$specItemId,'store_id'=>$store_id,'goods_id'=>$goodsId,'src'=>$datum['src']]);
                }
            }

            //同步规格价格
            if(isset($data['spec_price'])){
                foreach ($data['spec_price'] as $datum){
                    $str = preg_replace("/[\S]*:/u", '~~~', $datum['key_name']);
                    $key_name = explode('~~~',$str);
                    unset($key_name[0]);
                    $keyId = '';
                    foreach ($key_name as $item){
//                        $name = explode(':',$item);
                        $spec_item = M('spec_item')->where(['item'=>$item,'store_id'=>$store_id,'goods_id'=>$goodsId])->find();
                        $keyId = $keyId.'_'.$spec_item['id'];
                    }
                    $keyId = substr($keyId,1);
                    if($keyId)
                        M('spec_goods_price')->add(['goods_id'=>$goodsId,'key'=>$keyId,'key_name'=>$datum['key_name'],
                            'price'=>$datum['price'],
                            'store_count'=>$datum['store_count'],
                            'bar_code'=> isset($datum['bar_code']) ? $datum['bar_code'] : '',
                            'qipi_num'=>$datum['qipi_num'],
                            'sku'=>$datum['sku'],
                            'store_id'=>$store_id,
                            'image'=>isset($datum['image']) ? $datum['image'] : '',
                        ]);
                }
            }

            $json_str = json_encode(['status'=>1,'data'=>['goods_name'=>$goods_name],'msg'=>$goods_name.'同步成功'],true);
            exit($json_str);
        }else{
            Log::record($_POST['goods_data'],'ERR');
            $json_str = json_encode(['status'=>0,'data'=>[],'msg'=>'找不到数据'],true);
            exit($json_str);
        }

    }

}